import cv2
import numpy as np

def apply_random_affine_transform(image, edge_size, max_translation, max_rotation, max_scale):
    # 获取图像尺寸
    height, width = image.shape[:2]

    # 创建仿射变换矩阵
    M = np.eye(2, 3, dtype=np.float32)

    # 计算随机变换参数
    translation = np.random.uniform(-max_translation, max_translation, size=(2,))
    rotation = np.random.uniform(-max_rotation, max_rotation)
    scale = np.random.uniform(1.0 - max_scale, 1.0 + max_scale)

    # 将变换参数应用到仿射变换矩阵
    M[:2, :3] = cv2.getRotationMatrix2D((width // 2, height // 2), rotation, scale)
    M[:, 2] += translation

    # 将图像除边缘部分以外的区域应用仿射变换
    image_transformed = cv2.warpAffine(image[edge_size:height-edge_size, edge_size:width-edge_size], M, (width, height))

    # 将变换后的图像与原始图像进行合并
    image_result = image.copy()
    image_result[edge_size:height-edge_size, edge_size:width-edge_size] = image_transformed[edge_size:height-edge_size, edge_size:width-edge_size]

    return image_result

# 读取像
image_path = 'D:/bitahub_data/123/out/00125/S125M1-124_tr1-tc2.png'  # 图像路径
image = cv2.imread(image_path)

# 定义参数
edge_size = 20  # 边缘大小，即不进行变换的区域的宽度
max_translation = 10  # 最大平移量
max_rotation = 10  # 最大旋转角度（以度为单位）
max_scale = 0.1  # 最大缩放比例

# 施加随机仿射变换
image_transformed = apply_random_affine_transform(image, edge_size, max_translation, max_rotation, max_scale)

cv2.imwrite("D:/bitahub_data/123/out/1.png",image_transformed)

# 显示原始图像和变换后的图像
#cv2.imshow('Original Image', image)
#cv2.imshow('Transformed Image', image_transformed)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
